package com.lu.netty.medium;


import com.lu.netty.annotation.Remote;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;
import java.util.Map;

/**
 * 中介者模式
 * @author xiaolu
 * @version 1.0
 * @date 2021-02-03 10:14
 */
@Component
public class InitialMedium implements BeanPostProcessor {

    // 初始化之前
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    // 初始化之后
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if (bean.getClass().isAnnotationPresent(Remote.class)) {
            // 把类上的方法保存起来
            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                // 把方法名字和类的全名组合在一起
                String key = bean.getClass().getInterfaces()[0].getName() + "." + method.getName();
                Map<String, BeanMethod> beanMap = com.lu.netty.medium.Media.beanMap;
                BeanMethod beanMethod = new BeanMethod();
                beanMethod.setBean(bean);
                beanMethod.setMethod(method);
                beanMap.put(key,beanMethod);
            }
        }
        return bean;
    }
}
